package cz.muni.fi.rum.domainmodel;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 *
 * @author pmikulasek
 */
public class ReflectorSession extends ReflectorComponent implements Paramatizeabel {

    public static final String SESSION_LISTENERS = "Session.listeners";
    private Map<Long, ReflectorListener> listeners;

    //TODO ===ReflectorSession=== pridat parametry pro session
    public ReflectorSession() {
        super();
        listeners = new HashMap<Long, ReflectorListener>();
    }

    public void addReflectorListener(ReflectorListener listener) {
        if (!listeners.containsKey(listener.getId())) {
            listeners.put(listener.getId(), listener);
        }
    }

    public void addAllReflectorListeners(ReflectorSession session) {
        for (ReflectorListener listener : session.getAllListeners()) {
            if (!listeners.containsKey(listener.getId())) {
                listeners.put(listener.getId(), listener);
            }
        }
    }

    public void removeReflectorListener(ReflectorListener listener) {
        listeners.remove(listener.getId());
    }

    public ReflectorListener getListenerByComponentId(Long id) {
        return listeners.get(id);
    }

    public Collection<ReflectorListener> getAllListeners() {
        return listeners.values();
    }

    public int size() {
        return listeners.size();
    }

    public boolean containsRelfectorListener(ReflectorListener listener) {
        return listeners.containsValue(listener);
    }

    /**
     * Metoda vrati mapu v ni nemusi byt zadne klice pokud jsou null
     * {@see #SESSION_LISTENERS}
     * - klic pod kterym jsou vypsany jmena vsech listeneru
     * a tim je popsan jmeno teto session
     * @return
     */
    @Override
    public Map<String, String> getAllParams() {
        if (listeners.isEmpty()) {
            return Collections.EMPTY_MAP;
        }
        StringBuilder buf = new StringBuilder();
        Iterator<ReflectorListener> iterator = listeners.values().iterator();
        while (iterator.hasNext()) {
            String name = iterator.next().getName();
            if (name != null) {
                buf.append(name);
                if (iterator.hasNext()) {
                    buf.append(",");
                }
            } else {
                if (buf.length() > 1) {
                    buf.deleteCharAt(buf.length() - 1);
                }
            }
        }
        if (buf.length() > 0) {
            HashMap<String, String> ret = new HashMap<String, String>(1);
            ret.put(SESSION_LISTENERS, buf.toString());
            return Collections.unmodifiableMap(ret);
        } else {
            return Collections.EMPTY_MAP;
        }
    }
}
